
package com.zy.gmall.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import redis.clients.jedis.Jedis;

import java.io.IOException;

public class DimUtil {
    public static JSONObject getDimInfo(Jedis jedis, Connection conn, String Namespace, String tableName, String skuId){
        //先去redis里面找没有再去hbase里面找，并且缓存到redis中
        //redis的key
        String key = tableName.toLowerCase() + ":" + skuId;
        JSONObject jsonObj;//redis的结果
        String jsonString;
        //从redis中获取
        jsonString = jedis.get(key);
        if (StringUtils.isNotEmpty(jsonString)){
            //不为空说明有 直接从redis拿
            System.out.println("redis!!!!!!!!!!!!!!!!!!!");
             jsonObj = JSON.parseObject(jsonString);
        }else {
            //为空 先去hbase找
            System.out.println("hbase!!!!!!!!!!!!!!!!!!!!!!!!");
             jsonObj = HbaseUtil.getDimInfoFromHbase(conn, Namespace, tableName, skuId);
            if (jsonObj != null){
                //放入redis
                jedis.setex(key,24 * 3600,jsonObj.toJSONString());
            }else {
                System.out.println("没有！！！！！！！！！！！！！！");
            }

        }
        return jsonObj;
    }

    //如果有修改删除缓存中的
    public static void delCached(String tableName,String rowkey){
        String key = tableName + ":" + rowkey;
        Jedis jedis = RedisUtil.getJedis();
        try {
            jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(jedis != null){
                System.out.println("~~~从Redis中清除缓存后，关闭资源~~~");
                RedisUtil.closeJedis(jedis);
            }
        }
    }
}
